package com.springboot.fluentmybatis.controller;

import com.springboot.fluentmybatis.dao.UserDao;
import com.springboot.fluentmybatis.entity.User;
import com.springboot.fluentmybatis.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @Author: TongRui乀
 * @Date: 2021/6/20 10:07
 * @description：
 */
@RestController
@RequestMapping("user")
public class UserController {

    @Autowired
    UserDao userDao;

    @Autowired
    UserMapper userMapper;

    @PostMapping(consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> add(@RequestBody User user){
        this.userDao.save(user);
        return ResponseEntity.ok(user);
    }

    @GetMapping("{id}")
    public ResponseEntity<User> get(@PathVariable Integer id){
        return ResponseEntity.ok(this.userDao.selectById(id));
    }

    @PostMapping(value = "add", consumes = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<User> addMapper(@RequestBody User user){
        this.userMapper.insert(user);
        return ResponseEntity.ok(user);
    }

    @GetMapping("queryByCondition")
    public ResponseEntity<User> queryByCondition(){
        return ResponseEntity.ok(this.userMapper.findOne(this.userMapper.query().where
                .isDeleted().eq(true).end().limit(1)));
    }

    @PutMapping("{id}")
    public ResponseEntity<Integer> delete(@PathVariable Integer id){
        return ResponseEntity.ok(this.userMapper
                                    .updateBy(this.userMapper.updater()
                                            .update
                                                .isDeleted().is(true)
                                            .end()
                                            .where()
                                                .id().eq(id)
                                            .end()));
    }
}
